package cn.qingfeng.nio.blocking.simpleio.nothread;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class BioClient {
    public static void main(String[] args) throws IOException {
        try (
                Socket socket = new Socket("localhost", 8080);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
        ) {
            System.out.println("已连接到服务端");
            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);// 发送消息到服务端
                String response = in.readLine();// 接收服务端的回复
                System.out.println(response);

                if ("exit".equalsIgnoreCase(userInput)) {
                    break; // 输入"exit"时断开连接
                }
            }
        } catch (UnknownHostException e) {
            System.err.println("无法找到服务端: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("与服务端通讯时发生错误: " + e.getMessage());
        }
    }
}